package com.carman.cmreader;


import android.util.Log;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TxtManager {

    public final int curPageMaxLines = 55;
    public static final int ERROR = -1;
    private ArrayList<String> list = new ArrayList<>();
    private String keyword = null;
    private int totalPages = 0;
    private boolean isMatchCase;
    private boolean bTestVar;

    /**
     * 读取文件内容
     * @param filePath
     * @throws IOException
     */
    public void loadFile(String filePath) {
        reset();

        try {
            BufferedReader br = new BufferedReader(new FileReader(filePath));
            String line; //一行字符串
            while ((line = br.readLine()) != null) {
                list.add(line);  //集合添加字符串
            }
            br.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        totalPages = list.size()%curPageMaxLines == 0?
                list.size()/curPageMaxLines:list.size()/curPageMaxLines + 1;
    }

    /**
     * 获取Page index的内容
     * @param index 页码 从0开始
     * @return
     */
    public String getPageCont(int index) throws ArrayIndexOutOfBoundsException{
        String curPageCont = "";
        int curPageStartLine = index*curPageMaxLines;

        if(curPageStartLine > list.size()){
            throw  new ArrayIndexOutOfBoundsException();
        }

        int endPageStartLine = curPageStartLine + curPageMaxLines;

        if(endPageStartLine >= list.size()){
            endPageStartLine = list.size();
        }

        for(int i = curPageStartLine;i < endPageStartLine;i++){

            String cont = "";
            if(keyword != null){
                cont = matcherSearchTitle(list.get(i),keyword);
            }else{
                cont = list.get(i);
            }
            curPageCont += cont + "<br/>";
        }
        return curPageCont;
    }

    /**
     * 搜索，并标注关键字颜色
     * @param title
     * @param keyword
     * @return
     */
    public String matcherSearchTitle(String title,String keyword){
        String content = title;
        String wordReg = "";
        if(!isMatchCase){
            wordReg = "(?i)";//用(?i)来忽略大小写
        }
        wordReg += keyword;
        StringBuffer sb = new StringBuffer();
        Matcher matcher = Pattern.compile(wordReg).matcher(content);
        while(matcher.find()){
            //这样保证了原文的大小写没有发生变化
            matcher.appendReplacement(sb, "<font color=\"#ff0014\">"+matcher.group()+"</font>");
        }
        matcher.appendTail(sb);
        content = sb.toString();
        Log.i("Utils", content);
        //如果匹配和替换都忽略大小写,则可以用以下方法
//        content = content.replaceAll(wordReg,"<font color=\"#ff0014\">"+keyword+"</font>");
        Log.i("Utils", content);
        return content;
    }

    /**
     * 设置关键字
     * @param kw
     */
    public void setKeyword(String kw){
        keyword = kw;
    }

    public void setMatchCase(boolean matchCase){
        isMatchCase = matchCase;
    }

    /**
     * 获取关键字所在的页
     * @param forward 搜寻顺序  true 前进搜索  false 回退搜索
     * @param pages 从0开始 至 N - 1
     * @return 返回所在页数
     */
    public int getKwPageIndex(boolean forward,int pages){

        if(keyword == null){
            return ERROR;
        }

        int i = pages*curPageMaxLines;
        boolean isFind = false;
        Log.i("carman","kw = " + keyword);

        String rlKw = keyword;
        if(!isMatchCase){
            rlKw = rlKw.toLowerCase();
        }

        if(forward){
            //正向搜索
            for(;i < list.size();i++){
                String cont = list.get(i);
                if(!isMatchCase){
                    cont = cont.toLowerCase();
                }
                if(cont.contains(rlKw)){
                    Log.i("carman","i:" + i + "cont:" + list.get(i).toString());
                    isFind = true;
                    break;
                }
            }
        }else{
            //逆向搜索
            for(;i > 0;i--){
                String cont = list.get(i);
                if(!isMatchCase){
                    cont = cont.toLowerCase();
                }
                if(cont.contains(rlKw)){
                    Log.i("carman","i:" + i + "cont:" + list.get(i).toString());
                    isFind = true;
                    break;
                }
            }
        }

        if(isFind) {
            return ((i+1) % curPageMaxLines == 0 ? i / curPageMaxLines + 2: i / curPageMaxLines + 1);
        }else{
            return ERROR;//失败
        }
    }

    /**
     * 获取总页数
     * @return
     */
    public int getTotalPages(){
        return totalPages;
    }

    private void reset(){
        list.clear();
        totalPages = 0;
        keyword = null;
    }

}
